"""
PyQt5版GUI工具
"""
import random
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from ui.Ui_main_window import Ui_MainWindow
import sys


class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        # 创建对象
        self.ui = Ui_MainWindow()
        # 初始化内容
        self.ui.setupUi(self)
        self.timer: QTimer = None
        self.selected_row = -1
        
        self.model_all = QStringListModel()
        self.model_result = QStringListModel()
        
        self.data_lst = []
        self.result_list = []
        self.random_arr = []
        
        self.ui.label_subtitle.setText(
            "深圳集成电路应用开发(含嵌入式)6期"
        )
        
        arr = [
            "第一组（李世斌）",
            "第二组（王佳豪）",
            "第三组（陈鑫杰）",
            "第四组（陈敬豪）",
            "第五组（胡健涵）",
            "第六组（张涛）",
            "第七组（冯嘉良）",
            "第八组（陈习佳）",
            "第九组（张智超）",
        ]
        self.init_data(arr)
                
        # 初始化ui
        self.init_ui()

    def init_data(self, arr):
        self.data_lst = arr
        self.model_all.setStringList(self.data_lst)
        # 根据data_lst个数,生成1. 2. 3.
        self.result_list = [f"{str(i+1)}. " for i in range(len(self.data_lst))]
        self.model_result.setStringList(self.result_list)
        self.random_arr = list(range(1, len(self.data_lst) + 1))

    def show_random_number(self):
        # 让lcdNumber开始随机产生并显示 1->len(self.data_lst) 内的数字, 间隔100ms
        self.rand_number = random.choice(self.random_arr)
        self.ui.lcdNumber.display(self.rand_number)

    def handle_random_result(self):
        # 将索引为self.selected_row数据从self.data_lst中删除
        row_info = self.data_lst.pop(self.selected_row)
        # 设置到self.result_lst的self.rand_number-1行
        self.result_list[self.rand_number-1] += row_info
        
        self.model_all.setStringList(self.data_lst)
        self.model_result.setStringList(self.result_list)
        
        self.ui.label_desc.setText(f"【{row_info}】 随机抽签成功!")
        # 将self.rand_number从self.random_arr中删除
        self.random_arr.remove(self.rand_number)
        
        if len(self.random_arr) == 0:
            # 如果self.random_arr为空, 显示 全部抽签完毕
            self.ui.label_desc.setText(f"全部抽签完毕!")

    def on_action(self):
        if self.timer is not None:
            self.timer.stop()
            self.timer = None
            self.ui.btn_action.setText("开始")
            self.statusBar().showMessage("结果已产出!", 3000)
            self.ui.lv_all.setEnabled(True)

            self.handle_random_result()
            return
        
        if len(self.data_lst) == 0:
            self.statusBar().showMessage("已全部抽签完毕!")
            return
        
        cur_row_index = self.ui.lv_all.currentIndex().row()
        if cur_row_index == -1:
            # self.statusBar().showMessage("请先选择一行!")
            # return
            # 选中第一行
            cur_row_index = 0
            self.ui.lv_all.setCurrentIndex(self.model_all.index(cur_row_index, 0))
            
        # 获取lv_all中当前选中的行号
        self.selected_row = cur_row_index
        
        # 获取lv_all中选中的文本
        selected_text = self.ui.lv_all.currentIndex().data()
        self.ui.label_desc.setText(f"【{selected_text}】 随机抽签中...\n按空格停止!")
        self.statusBar().showMessage("随机中, 按空格停止!")
        self.ui.btn_action.setText("停止")
        # 禁用lv_all点击事件
        self.ui.lv_all.setEnabled(False)
        
        # 开启定时器QTimer, 每50ms调用一次 show_random_number
        self.timer = QTimer(self)
        self.timer.setInterval(50)
        self.timer.timeout.connect(self.show_random_number)
        self.timer.start()
        
    def on_export(self):
        # 将self.result_list转为字符串列表, 存储到选定文件中
        filePath = QFileDialog.getSaveFileName(self, "保存文件", "", "Text Files (*.txt)")
        if filePath[0] == "":
            return
        
        with open(filePath[0], "w") as f:
            f.write("\n".join(self.result_list))
    
    def on_import(self):
        # 选择文件
        filePath = QFileDialog.getOpenFileName(self, "导入文件", "", "Text Files (*.txt)")
        if filePath[0] == "":
            return
        
        with open(filePath[0], "r") as f:
            lines = f.readlines()
            # 去除空行, 移除每行的空白
            lines = [line.strip() for line in lines if line.strip()]
            if len(lines) == 0:
                return
                        
            self.init_data(lines)

    def init_ui(self):
        self.ui.lv_all.setModel(self.model_all)
        self.ui.lv_result.setModel(self.model_result)
        self.ui.btn_action.clicked.connect(self.on_action)
        self.ui.btn_export.clicked.connect(self.on_export)
        self.ui.btn_import.clicked.connect(self.on_import)
        
        

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()